<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索 -->
    <el-card class="box-card">
      <div slot="header">
        <el-input placeholder="请输入搜索内容" class="inputWidth" v-model="queryInfo.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
        </el-input>
        <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
      </div>

      <!-- table区 -->

      <el-table border style="width: 100%" :data="userList">
        <el-table-column type='index' width="50">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="130">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="140">
        </el-table-column>
        <el-table-column label="状态" width="180">
          <template slot-scope="{row}">
            <el-switch v-model="row.mg_state" @change="userStateChange(row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="{row}">
            <!-- 修改用户 -->
            <div>
              <el-button type="primary" class="el-icon-edit" size="mini" @click="editShowDialog(row, $index)">
              </el-button>
              <!-- 删除操作 -->
              <el-button type="danger" class="el-icon-delete" size="mini" @click="deleteUserList(row.id)"></el-button>

              <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
                <el-button type="warning" class="el-icon-s-tools" size="mini" @click="setRights(row)"></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 3, 5, 10]" :page-size="queryInfo.pagesize"
        layout=" prev, pager, next, jumper,sizes,total" :total="total">
      </el-pagination>
      <!-- dialog对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="40%" @close="addDialogClosed">
        <el-form ref="ruleFormRef" label-width="80px" :rules="addUserRules" class="demo-ruleForm" :model="addForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUsers">确 定</el-button>
        </span>
      </el-dialog>
      <!-- //修改用户对话框 -->
      <el-dialog title="修改信息" :visible.sync="editDialogVisible" width="40%">
        <el-form ref="editruleForm" label-width="70px" :rules="addUserRules" :model="oldUserMsg">
          <el-form-item label="用户名">
            <el-input v-model="oldUserMsg.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="oldUserMsg.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="oldUserMsg.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cleanShowDialog">取 消</el-button>
          <el-button type="primary" @click="editDialogUser">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsdialogVisible" width="30%" @close="rolesListClose">
      <div>
        <p>当前的用户:{{userInfo.username}}</p>
        <p>当前的角色:{{userInfo.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option v-for="item in setRolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="assignRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data() {
      // 自定义验证规则
      var mobileRules = (rule, value, cb) => {
        const regMobile =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (regMobile.test(value)) {
          return cb()
        }
        cb(new Error('请输入合法的手机号'))
      }
      return {
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 5,
        },
        userList: [],
        total: 0,
        addDialogVisible: false,
        setRightsdialogVisible: false,
        addUserRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 6, message: '请输入3-6位字符', trigger: 'blur' },
          ],
          password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
          email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            {
              type: 'email',
              message: '请输入正确的邮箱地址',
              trigger: ['blur', 'change'],
            },
          ],
          mobile: [
            { required: true, message: '请输入电话', trigger: 'blur' },
            { validator: mobileRules, trigger: 'blur' },
          ],
        },
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: '',
        },
        editDialogVisible: false,
        oldUserMsg: {},
        userInfo: {},
        setRolesList: [],
        selectRoleId: '',
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      async getUserList() {
        let { data: res } = await this.$http.get('users', {
          params: this.queryInfo,
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.userList = res.data.users
        this.total = res.data.total
      },
      handleSizeChange(val) {
        this.queryInfo.pagesize = val
        this.getUserList()
      },
      handleCurrentChange(val) {
        this.queryInfo.pagenum = val
        this.getUserList()
      },
      async userStateChange(row) {
        let { data: res } = await this.$http.put(
          `users/${row.id}/state/${row.mg_state}`
        )
        if (res.meta.status !== 200) {
          row.mg_state = !row.mg_state
          return this.$message.error('修改失败')
        }
        this.$message.success('更新状态成功')
      },
      addDialogClosed() {
        this.$refs.ruleFormRef.resetFields()
      },
      addUsers() {
        this.$refs.ruleFormRef.validate(async (valid, obj) => {
          if (!valid) return
          let { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功')
          this.getUserList()
        })
        this.addDialogVisible = false
      },
      async editShowDialog(row, index1) {
        let { data: res } = await this.$http.get(`users/${row.id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('获取信息失败')
        }
        this.oldUserMsg = res.data
        console.log(this.oldUserMsg)
        this.editDialogVisible = true
      },
      cleanShowDialog() {
        this.$refs.editruleForm.resetFields()
        this.editDialogVisible = false
      },
      editDialogUser() {
        this.$refs.editruleForm.validate(async (vaild) => {
          if (!vaild) return
          let { data: res } = await this.$http.put(
            `users/${this.oldUserMsg.id}`,
            { email: this.oldUserMsg.email, mobile: this.oldUserMsg.mobile }
          )
          if (res.meta.status !== 200) {
            return this.$message.error('修改想信息失败')
          }
          this.$message.success('修改成功')
          this.getUserList()
        })
        this.editDialogVisible = false
      },
      async deleteUserList(id) {
        const confirmRes = await this.$confirm(
          '此操作将永久删除, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).catch((err) => err)
        if (confirmRes !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        let { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.getUserList()
        this.$message.success('删除成功!')
      },
      async setRights(row) {
        this.userInfo = row

        let { data: res } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error('获取失败')
        }
        this.setRolesList = res.data

        this.setRightsdialogVisible = true
      },
      async assignRoles() {
        if (!this.selectRoleId) {
          return this.$message.warning('请选择角色')
        }
        let { data: res } = await this.$http.put(
          `users/${this.userInfo.id}/role`,
          { rid: this.selectRoleId }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('分配失败')
        }
        this.$message.success('分配成功')
        this.getUserList()
        this.setRightsdialogVisible = false
      },
      rolesListClose() {
        this.userInfo = {}
        this.selectRoleId = ''
      }
    },
  }
</script>
<style lang="less" scoped>
  .box-card {
    margin: 15px 0;

    .inputWidth {
      width: 300px;
      margin-right: 15px;
    }
  }
</style>
<style>
  .el-card__header {
    border-bottom: none;
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
</style>